package com.dongdongshop.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.dongdongshop.data.Result;
import com.dongdongshop.data.ResultEnum;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
@RequestMapping("file")
public class FileController {

    @RequestMapping("upload")
    @ResponseBody
    public Result upload(@RequestParam("itemImages")MultipartFile itemImages){
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            String http = "https://";
            String endpoint = "oss-cn-beijing.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            String accessKeyId = "LTAI5tEbDYidRrJAn2rXamuL";
            String accessKeySecret = "2laTdnF3iQrt02jnX8xoU3WJoqCUxi";
// 填写Bucket名称，例如examplebucket。
            String bucketName = "dk2105lya";
// 填写文件名。文件名包含路径，不包含Bucket名称。例如exampledir/exampleobject.txt。
            String objectName = "image/"+itemImages.getOriginalFilename();

            OSS ossClient = null;
            try {
                // 创建OSSClient实例。
                ossClient = new OSSClientBuilder().build(http+endpoint, accessKeyId, accessKeySecret);

                ossClient.putObject(bucketName, objectName, itemImages.getInputStream());
            } catch (OSSException e){
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭OSSClient。
                ossClient.shutdown();
            }
            String url = http + bucketName + "." + endpoint + "/" +objectName;
            return Result.respones(ResultEnum.SUCCESS).setData(url);

    }
}
